package jkclient

import (
	"jkgo/jk/jklog"
	"jkgo/jk/jkprotocol"
	b "findService/ss/servicebase"
	"time"
)

const (
	service_selfname = "jkclient"
)

type DemoClient struct {
	b.ClientBase

	iotclient *b.SSIoTClient
}

func NewDemoClient(addr string, port int) (*DemoClient, error) {
	c := &DemoClient{}
	err := c.New(addr, port, 1)
	if err != nil {
		return nil, err
	}
	go c.DialDuring(5)

	return c, nil
}

func (dc *DemoClient) DealResponse(msg string) {
	p, err := jkprotocol.JKProtoV6Parse(msg)
	if err == nil {
		if p.H.R {
			s, _ := p.JKProtoV6MakeTR(service_selfname, false, p.B)
			jklog.L().Debugln("jkclient send response out")
			dc.Send(s)
		}
	} else {
		jklog.L().Errorln("parse message err ", err)
	}
}

func (dc *DemoClient) DealRecv() {
	jklog.L().Debugln("client recv start")
	for {
		d, err := dc.RecvClient()
		if err != nil {
			jklog.L().Errorln("Recv error ", err)
			time.Sleep(1 * time.Second)
			continue
		}
		jklog.L().Debugln("recv data ", string(d))
		dc.DealResponse(string(d))
	}
}
